"""
独立的邮件同步服务
与FastAPI应用分离，单独运行以避免多worker冲突
"""
import asyncio
import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from api.utils.logger import get_logger
from api.service.sync_manager import sync_manager
from api.database import SessionLocal
# 导入所有模型，确保SQLAlchemy能够正确初始化所有关系
from api.model.user import User
from api.model.email_account import EmailAccount
from api.model.email_folder import EmailFolder
from api.model.email import Email
from api.model.draft import Draft
from api.model.proxy import Proxy
from api.model.translation_config import TranslationConfig

logger = get_logger("sync_service")
sync_logger = get_logger("sync")


async def main():
    """主函数"""
    sync_logger.info("=" * 60)
    sync_logger.info("邮件同步服务启动中...")
    sync_logger.info("=" * 60)
    
    try:
        # 检查数据库连接
        db = SessionLocal()
        try:
            account_count = db.query(EmailAccount).count()
            sync_logger.info(f"数据库连接成功，共有 {account_count} 个邮箱账户")
        finally:
            db.close()
        
        # 启动同步管理器
        await sync_manager.start()
        sync_logger.info("邮件同步服务已启动，按 Ctrl+C 停止")
        
        # 保持服务运行
        while True:
            await asyncio.sleep(60)
            # 每分钟输出一次心跳日志
            status = sync_manager.get_status()
            sync_logger.info(f"同步服务运行中 - 活跃任务: {status['active_tasks']}, 同步间隔: {status['sync_interval']}s")
    
    except KeyboardInterrupt:
        sync_logger.info("收到停止信号，正在关闭同步服务...")
    except Exception as e:
        logger.error(f"同步服务异常: {e}", exc_info=True)
        raise
    finally:
        # 停止同步管理器
        try:
            await sync_manager.stop()
            sync_logger.info("邮件同步服务已停止")
        except Exception as e:
            logger.error(f"停止同步管理器失败: {e}", exc_info=True)


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        sync_logger.info("同步服务已退出")
    except Exception as e:
        logger.error(f"同步服务启动失败: {e}", exc_info=True)
        sys.exit(1)